/*
 * @Description: 顺风车地图组件   IndexCarpoolMap
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-10-30 09:32:13
 * @LastAuthor   : zhengzhuang
 * @lastTime     : 2020-01-08 16:47:43
 */
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/event/event_bus.dart';
import 'package:C20Driver/model/user_realtime_location_model.dart';
import 'package:C20Driver/utils/permission_handler.dart';

class IndexCarpoolMap extends StatefulWidget {
  final callBackAmapController;
  final callBackStart;
  final callBack;
  IndexCarpoolMap(
      {this.callBackStart, this.callBack, this.callBackAmapController});
  @override
  _IndexCarpoolMapState createState() => _IndexCarpoolMapState();
}

class _IndexCarpoolMapState extends State<IndexCarpoolMap>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  @override
  bool get wantKeepAlive => true;
  AmapController _amapController;

  @override
  void initState() {
    super.initState();
    eventBus.on<SetMapLocation>().listen((event) async {
      /// 设置当前我的位置
      _amapController.setCenterCoordinate(
          LatLng(event.latlng.latitude, event.latlng.longitude));

      /// 设置缩放级别
      /// 延时1s执行返回
      Future.delayed(Duration(seconds: 1), () async {
        /// 设置缩放级别
        await _amapController.setZoomLevel(15.0);
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _amapController.dispose();
    // _amapController = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      width: ScreenUtil().setWidth(750.0),
      height: double.infinity,
      child: Stack(
        children: <Widget>[
          AmapView(
            // 地图类型
            mapType: MapType.Standard,
            // 是否显示缩放控件
            showZoomControl: true,
            // 是否显示指南针控件
            showCompass: true,
            // 是否显示比例尺控件
            showScaleControl: true,
            // 是否使能缩放手势
            zoomGesturesEnabled: true,
            // 是否使能滚动手势
            scrollGesturesEnabled: true,
            // 是否使能旋转手势
            rotateGestureEnabled: true,
            // 是否使能倾斜手势
            tiltGestureEnabled: true,
            // 缩放级别
            zoomLevel: 17.0,
            onMapCreated: (controller) async {
              _amapController = controller;
              widget.callBackAmapController(_amapController);
              if (await PermissionHandlerX.position(context)) {
                await AmapLocation.fetchLocation().then((res) {
                  print(LatLng(res.latLng.latitude, res.latLng.longitude));

                  /// 设置当前我的位置
                  _amapController.setCenterCoordinate(
                      LatLng(res.latLng.latitude, res.latLng.longitude));
                });
              }
            },
            onMapMoveStart: (drag) async {
              widget.callBackStart();
            },
            onMapMoveEnd: (drag) async {
              await AmapSearch.searchReGeocode(
                LatLng(
                  double.parse(drag.latLng.latitude.toString()),
                  double.parse(drag.latLng.longitude.toString()),
                ),
                radius: 200.0,
              ).then((res) async {
                /// 设置用户出发位置地点
                var lat = {
                  'lat': double.parse(drag.latLng.latitude.toString()),
                  'lng': double.parse(drag.latLng.longitude.toString()),
                  'name': await res.formatAddress,
                  'cityName': await res.cityName,
                };
                var latDataJson = UserRealtimeLocationModel.fromJson(lat);
                widget.callBack(latDataJson);
              });
            },
            onMapClicked: (latLng) {
              return;
            },
          ),
          Positioned(
            top: 0,
            bottom: 0,
            left: 0,
            right: 0,
            child: Stack(
              children: <Widget>[
                Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(
                    bottom: ScreenUtil().setWidth(83.0),
                  ),
                  child: Container(
                    child: Image.asset(
                      'assets/icon/coordinatePointsIcon.png',
                      width: ScreenUtil().setWidth(60.0),
                      height: ScreenUtil().setWidth(83.0),
                    ),
                  ),
                ),
                Positioned(
                  top: ScreenUtil().setHeight(150.0),
                  right: ScreenUtil().setHeight(20.0),
                  child: MaterialButton(
                    minWidth: ScreenUtil().setHeight(80.0),
                    height: ScreenUtil().setHeight(80.0),
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(100.0)),
                    ),
                    child: Icon(Icons.my_location),
                    onPressed: () async {
                      if (await PermissionHandlerX.position(context)) {
                        /// 获取我的定位
                        await AmapLocation.fetchLocation().then((res) {
                          /// 设置当前我的位置
                          _amapController.setCenterCoordinate(LatLng(
                              res.latLng.latitude, res.latLng.longitude));
                          // 延时1s执行返回
                          Future.delayed(Duration(seconds: 1), () async {
                            // 设置缩放级别
                            await _amapController.setZoomLevel(15.0);
                          });
                        });
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
